package com.sander.guardmanagement.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sander.guardmanagement.R;
import com.sander.guardmanagement.http.BaseCallback;
import com.sander.guardmanagement.http.HttpApi;
import com.sander.guardmanagement.http.OkHttpHelper;
import com.sander.guardmanagement.http.UserLogin;
import com.sander.guardmanagement.http.UserReg;
import com.sander.guardmanagement.http.UserSendsms;
import com.sander.guardmanagement.response.ResponseUserLogin;
import com.sander.guardmanagement.response.ResponseUserLoginData;
import com.sander.guardmanagement.response.ResponseUserReg;
import com.sander.guardmanagement.response.ResponseUserSendsms;
import com.sander.guardmanagement.until.AppUnit;
import com.sander.guardmanagement.until.UserInfoManager;
import com.sander.guardmanagement.widgets.AndroidBug5497Workaround;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.util.Timer;
import java.util.TimerTask;

import bolts.Task;
import mehdi.sakout.dynamicbox.DynamicBox;

public class SDLoginActivity extends AppCompatActivity implements View.OnLayoutChangeListener {
    LinearLayout loginMenutView;
    LinearLayout regiestMenutView;

    LinearLayout loginView;
    LinearLayout regiestView;

    ImageView point_login;
    ImageView point_regiest;


    // 登录模块的
    EditText input_user_name_login_editview;
    EditText input_user_password_login_editview;
    Button login_action_button;

    //注册模块的
    EditText input_user_name_regiest_editview;
    TextView get_smsCode_button;
    EditText input_user_sms_code_editview;
    EditText input_user_password_regiest_editeView;
    Button regiest_action_button;

    TextView forget_password_button;

    ImageView check_out;

    String sms_id;

    DynamicBox box;

    private int timeCount = 300;
    private Timer mtimer;
    //Activity最外层的Layout视图
    private RelativeLayout activityRootView;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    boolean islogin  =true;

    int usedsafeheight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sdlogin);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        initView();

        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;
//        AndroidBug5497Workaround.assistActivity(this);

        activityRootView = (RelativeLayout) findViewById(R.id.screentViewlayout);

        activityRootView.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(View oldFocus, View newFocus) {
                Rect rect = new Rect();
                activityRootView.getWindowVisibleDisplayFrame(rect);
                int mainInvisibleHeight = activityRootView.getRootView().getHeight() - (rect.bottom - rect.top);
                Log.d("sander",mainInvisibleHeight + " ----> ");
                if (mainInvisibleHeight > 100) {
                    int[] location = new int[2];
                    if (islogin){
                        input_user_password_login_editview.getLocationInWindow(location);
                        int srollHeight = (location[1] + input_user_password_login_editview.getHeight()) - rect.bottom;
                        if (srollHeight > 0 ){
                            activityRootView.scrollTo(0, srollHeight);
                        }else{
                            activityRootView.scrollTo(0,0);
                            Log.d("sander","这个执行吗");
                        }
                    }else{
                        input_user_password_regiest_editeView.getLocationInWindow(location);
                        int srollHeight = (location[1] + input_user_password_regiest_editeView.getHeight()) - rect.bottom;
                        if (srollHeight > 0){
                            activityRootView.scrollTo(0, srollHeight);
                        }else {
                            activityRootView.scrollTo(0,0);
                        }
                    }
                    usedsafeheight = mainInvisibleHeight;
                } else {
                    usedsafeheight = 0;
                    activityRootView.scrollTo(0, 0);
                }

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
//        //添加layout大小发生改变监听器
//        activityRootView.addOnLayoutChangeListener(this);
    }

    private void initView()
    {

        box = new DynamicBox(this, R.layout.activity_sdlogin);

        point_login = (ImageView)findViewById(R.id.selected_menu_login);
        point_regiest = (ImageView) findViewById(R.id.selected_menu_regiest);

        input_user_name_login_editview = (EditText) findViewById(R.id.et_login_username);
        input_user_password_login_editview = (EditText) findViewById(R.id.et_login_pwd);
        login_action_button = (Button) findViewById(R.id.btn_login);

        input_user_name_regiest_editview = (EditText)findViewById(R.id.inputusernameedittext) ;
        get_smsCode_button = (TextView) findViewById(R.id.tv_get_smscode) ;
        input_user_sms_code_editview = (EditText) findViewById(R.id.et_reg_smscode) ;
        input_user_password_regiest_editeView = (EditText)findViewById(R.id.et_reg_password);

        regiest_action_button = (Button) findViewById(R.id.reg_confirm) ;

        loginView = (LinearLayout) findViewById(R.id.loginView);
        regiestView = (LinearLayout)findViewById(R.id.registerView);
        loginMenutView = (LinearLayout) findViewById(R.id.loginMenutForm);
        regiestMenutView  = (LinearLayout) findViewById(R.id.registeredMenutForm);
        loginMenutView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginView.setVisibility(View.VISIBLE);
                regiestView.setVisibility(View.GONE);
                showPointForLogin();
                islogin = true;
//                AppUnit.showSoftInputFromWindow((Activity) getApplicationContext(), input_user_password_login_editview);
            }
        });

        regiestMenutView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginView.setVisibility(View.GONE);
                regiestView.setVisibility(View.VISIBLE);
                showPointForRegiest();
                islogin = false;
//                AppUnit.showSoftInputFromWindow((Activity) getApplicationContext(), input_user_password_regiest_editeView);

            }
        });
        // 默认先显示登录的
        this.showPointForLogin();


        login_action_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoginAction();
            }
        });
        get_smsCode_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onGetSMSCode();
            }
        });

        regiest_action_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRegiestAction();
            }
        });


        forget_password_button = (TextView)findViewById(R.id.forget_password_button);
        forget_password_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // forget password
                Intent intent = new Intent(SDLoginActivity.this,RegisteredActivity.class);
                Bundle bundle = new Bundle();
                bundle.putBoolean("ischange",true);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });


        check_out = (ImageView) findViewById(R.id.checkbox_button);
        check_out.setSelected(true);
        check_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isCheckout = check_out.isSelected();
                check_out.setSelected(!isCheckout);
            }
        });

        UserInfoManager userInfoManager = UserInfoManager.sharedManager();
        userInfoManager.checkoutFuckSaveuserInfo(getApplicationContext());
        if (userInfoManager.fuck_phone!=null) input_user_name_login_editview.setText(userInfoManager.fuck_phone);

        if (userInfoManager.fuck_passworld != null) input_user_password_login_editview.setText(userInfoManager.fuck_passworld);

//        AppUnit.showSoftInputFromWindow(this, input_user_password_login_editview);

    }

    public void showPointForLogin(){
        point_login.setVisibility(View.VISIBLE);
        point_regiest.setVisibility(View.GONE);
    }
    public void showPointForRegiest(){
        point_regiest.setVisibility(View.VISIBLE);
        point_login.setVisibility(View.GONE);
    }

    public void onLoginAction()
    {
        final String user_name = input_user_name_login_editview.getText().toString();
        final String user_password = input_user_password_login_editview.getText().toString();
        if (TextUtils.isEmpty(user_name)){
            showToastMessage("用户名不能为空");
            return;
        }
        if (TextUtils.isEmpty(user_password)){
            showToastMessage("密码不能为空");
            return;
        }
        UserLogin userLogin = new UserLogin();userLogin.phone = user_name;userLogin.password = AppUnit.getSha1(user_password);
        OkHttpHelper.getinstance().post(HttpApi.getAPiUrl(HttpApi.User_login), userLogin.getValueOfClas(), new BaseCallback<ResponseUserLogin>() {
        @Override    public void onRequestBefore() {
            showProgress(true);
        }

        @Override    public void onFailure(Request request, Exception e) {
            showProgress(false);
        }

        @Override    public void onSuccess(Response response, ResponseUserLogin o) {

            if (o.getCode() == 0){
                ResponseUserLoginData userinfo = o.getData();
                UserInfoManager.sharedManager().setUserInfo(userinfo);
                UserInfoManager.sharedManager().saveUserInfo(userinfo.getPhone(),userinfo.getId() + "",getApplicationContext());

                if (check_out.isSelected()){
                    UserInfoManager.sharedManager().saveFuckUserInfo(user_name,user_password,getApplicationContext());
                }else{
                    UserInfoManager.sharedManager().saveFuckUserInfo(user_name,null,getApplicationContext());

                }
                Intent intent  = new Intent(SDLoginActivity.this,MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                showProgress(false);

            }else{
                showToastMessage(o.getMsg());
                showProgress(false);

            }
        }

        @Override    public void onError(Response response, int errorCode, Exception e) {
            showProgress(false);
        }
    });

    }

    public void onGetSMSCode(){
        String phone_string = input_user_name_regiest_editview.getText().toString();
        if (TextUtils.isEmpty(phone_string)){
            showToastMessage("用户名不能为空");
            return;
        }

        UserSendsms userSendsms = new UserSendsms(phone_string);

        OkHttpHelper.getinstance().post(HttpApi.getAPiUrl(HttpApi.SMS_verification_code), userSendsms.getValueOfClas(), new BaseCallback<ResponseUserSendsms>() {
            @Override
            public void onRequestBefore() {
                Log.d("sander","on request before");
            }

            @Override
            public void onFailure(Request request, Exception e) {
                Log.d("sander","on failure");
                regiest_action_button.setEnabled(false);
            }

            @Override
            public void onSuccess(Response response, ResponseUserSendsms responseUserSendsms) {
                if (responseUserSendsms.getCode() == 0){
                    Log.d("sander",responseUserSendsms.msg);
                    Log.d("sander",responseUserSendsms.getData().getPhone());
                    sms_id = responseUserSendsms.getData().getSms_id();
                    startCountdown();
                }else{
                    showToastMessage(responseUserSendsms.getMsg());

                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }
    public void onRegiestAction(){
        String phone_string = input_user_name_regiest_editview.getText().toString();
        if (TextUtils.isEmpty(phone_string)){
            showToastMessage("用户名不能为空");
        }

        String sms_code_string = input_user_sms_code_editview.getText().toString();
        if (TextUtils.isEmpty(sms_code_string)){
            showToastMessage("验证码不能为空");
        }

        String password_string = input_user_password_regiest_editeView.getText().toString();
        if (TextUtils.isEmpty(password_string)){
            showToastMessage("密码不能为空");
        }


        UserReg userReg = new UserReg();
        userReg.phone = phone_string;
        userReg.password = AppUnit.getSha1(password_string);
        userReg.sms_id = sms_id;
        userReg.sms_code = sms_code_string;

        OkHttpHelper.getinstance().post(HttpApi.getAPiUrl(HttpApi.User_registration), userReg.getValueOfClas(), new BaseCallback<ResponseUserReg>() {
            @Override
            public void onRequestBefore() {
                showProgress(true);
            }

            @Override
            public void onFailure(Request request, Exception e) {
                showProgress(false);
            }

            @Override
            public void onSuccess(Response response, ResponseUserReg o) {
                showProgress(false);
                Log.d("sander",o.getMsg());
                if (o.getCode() == 0){
                    Log.d("sander",o.getMsg());
                    Log.d("sander",o.getData().getId() + "");
                    String user_account = o.getData().getPhone();
                    String user_id = String.valueOf(o.getData().getId());

                    UserInfoManager.sharedManager().saveUserInfo(user_account,user_id,getApplicationContext());

                    Intent intent  = new Intent(SDLoginActivity.this,MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }else{
                    showToastMessage(o.getMsg());
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }

    public void showProgress(boolean show){
        if (show ){
            box.showLoadingLayout();
        }else{
            box.hideAll();
        }
    }

    public void showToastMessage(String message){
        Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();

    }

    public void startCountdown(){
        regiest_action_button.setEnabled(true);
        changeSmsButton();
        get_smsCode_button.setEnabled(false);
        setTimerTask();
    }
    public void setTimerTask(){
        mtimer = new Timer();
        mtimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                timerHandler.sendMessage(message);
            }
        },1000,1000);
    }
    public void changeSmsButton(){
        get_smsCode_button.setText(timeCount + "秒重发");

    }
    private Handler timerHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1){
                timeCount --;
                if (timeCount >= 0){
                    changeSmsButton();
                }else{
                    mtimer.cancel();
                    get_smsCode_button.setEnabled(true);
                    get_smsCode_button.setText(R.string.getsmsversion);
//                    okButton.setEnabled(true);
//                    okButton.setText(R.string.getsmsversion);
                }
            }
        }
    };


    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){

            Toast.makeText(SDLoginActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();

        }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){

            Toast.makeText(SDLoginActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();

        }
    }
}
